package org.jeecg.modules.supplier.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.file.entity.ProcurementFile;
import org.jeecg.modules.file.service.IProcurementFileService;
import org.jeecg.modules.message.entity.ProcurementMessage;
import org.jeecg.modules.message.service.IProcurementMessageService;
import org.jeecg.modules.supplier.Vo.SupplierMatchVo;
import org.jeecg.modules.supplier.Vo.SupplierVo;
import org.jeecg.modules.supplier.entity.ProcUserSupplierRelation;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.entity.qualification;
import org.jeecg.modules.supplier.service.IProcUserSupplierRelationService;
import org.jeecg.modules.supplier.service.IQualificationService;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(tags = "供应商管理66")
@RestController
@RequestMapping("/procurement/supplier")
@Slf4j
public class SupplierController extends JeecgController<Supplier, ISupplierService> {

    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private IProcUserSupplierRelationService procUserSupplierRelationService;
    @Autowired
    private IProcurementMessageService procurementMessageService;
    @Autowired
    private IProcurementFileService procurementFileService;

    @Autowired
    private IQualificationService qualificationService;



    @AutoLog(value = "供应商-分页列表查询")
    @ApiOperation(value = "供应商-分页列表查询", notes = "供应商-分页列表查询")
    @GetMapping(value = "/list")
    public Result<Page<Supplier>> queryPageList(@RequestParam(defaultValue = "1") Integer pageNo,
                                                @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Supplier> page = new Page<>(pageNo, pageSize);

        // 创建查询条件包装器并设置按创建时间降序排序
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");

        page = supplierService.page(page, queryWrapper);
        if (page.getTotal() == 0){
            return Result.OK("未查询到供应商数据", page); // 更新提示信息为更具体的内容
        }
        return Result.OK(page);
    }

    @AutoLog(value = "供应商-添加")
    @ApiOperation(value = "供应商-添加", notes = "供应商-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SupplierVo supplierVo) {
        // 添加空值校验
        if (supplierVo == null) {
            log.warn("【供应商】添加失败: 供应商数据为空");
            return Result.error("供应商数据不能为空");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        if (StringUtils.isEmpty(supplierVo.getCreditCode())) {
            log.warn("【供应商】添加失败: 统一社会信用代码不能为空");
            return Result.error("统一社会信用代码不能为空");
        }

        if (supplierService.checkCreditCodeExists(supplierVo.getCreditCode(), null)) {
            return Result.error("统一社会信用代码已存在");
        }

        // 将Vo转换为实体
        Supplier supplier = new Supplier();
        // 复制属性
        BeanUtils.copyProperties(supplierVo, supplier);
        // 设置创建人信息
        supplier.setCreateBy(sysUser.getUsername());

        // 先保存供应商主体信息，获取生成的ID
        if(supplierService.saveSupplier(supplier)){
            // 再保存资质信息（如果有）
            if (supplierVo.getQualifications() != null && !supplierVo.getQualifications().isEmpty()) {
                // 调用服务层方法处理资质信息
                supplierService.saveSupplierQualifications(supplierVo.getQualifications(), supplier.getId());
                qualificationService.saveBatch(supplierVo.getQualifications());
            }

            return Result.OK("新添成功");
        }
        //保存主要资质在供应商
        return Result.error("新添失败");


    }

    @AutoLog(value = "供应商-编辑")
    @ApiOperation(value = "供应商-编辑", notes = "供应商-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SupplierVo supplierVo) {
        // 添加空值校验
        if (supplierVo == null) {
            log.warn("【供应商】编辑失败: 供应商数据为空");
            return Result.error("供应商数据不能为空");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        if (StringUtils.isEmpty(supplierVo.getCreditCode())) {
            log.warn("【供应商】编辑失败: 统一社会信用代码不能为空");
            return Result.error("统一社会信用代码不能为空");
        }

        // 将Vo转换为实体
        Supplier supplier = supplierService.getById(supplierVo.getId());
        // 复制属性
        BeanUtils.copyProperties(supplierVo, supplier);
        // 设置更新人信息
        supplier.setUpdateBy(sysUser.getUsername());
        supplier.setAuditStatus("0");
        supplier.setUpdateTime(new Date());
        // 调用service更新
        boolean Resul = supplierService.updateSupplier(supplier);
        // 再保存资质信息（如果有）
        if (supplierVo.getQualifications() != null && !supplierVo.getQualifications().isEmpty()) {
            // 调用服务层方法处理资质信息
            supplierService.saveSupplierQualifications(supplierVo.getQualifications(), supplier.getId());
             qualificationService.updatequalification(supplierVo.getQualifications(), supplier.getId());//批量更新:根据supplier_id批量更新proc_qualification表中对应的多条数据
        }
        if(Resul){
            return Result.OK("编辑成功");
        }

        return Result.error("编辑失败");
    }

    @AutoLog(value = "供应商-通过id删除")
    @ApiOperation(value = "供应商-通过id删除", notes = "供应商-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        // 添加ID空值校验
        if (StringUtils.isEmpty(id)) {
            log.warn("【供应商】删除失败: ID不能为空");
            return Result.error("ID不能为空");
        }
        supplierService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "供应商-批量删除")
    @ApiOperation(value = "供应商-批量删除", notes = "供应商-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        // 添加ID列表空值校验
        if (StringUtils.isEmpty(ids)) {
            log.warn("【供应商】批量删除失败: IDs不能为空");
            return Result.error("IDs不能为空");
        }
        this.supplierService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @AutoLog(value = "供应商-通过id查询")
    @ApiOperation(value = "供应商-通过id查询", notes = "供应商-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        // 添加ID空值校验
        if (StringUtils.isEmpty(id)) {
            log.warn("【供应商】查询失败: ID不能为空");
            return Result.error("ID不能为空");
        }
        Supplier supplier = supplierService.getById(id);
        if (supplier == null) {
            return Result.error("未找到对应数据");
        }
        SupplierVo supplierVo =new SupplierVo();
        // 复制属性
        BeanUtils.copyProperties(supplier, supplierVo);

        List<ProcurementFile> file = procurementFileService.getFilesByBiz(id,"supplier");
        supplierVo.setProcurementFile(file);
        List<qualification> qualifications = qualificationService.getQualificationList(id);
        supplierVo.setQualifications(qualifications);
        return Result.OK(supplierVo);
    }

    @AutoLog(value = "供应商-审核/入库")
    @ApiOperation(value = "供应商-审核/入库", notes = "供应商-审核/入库")
    @PostMapping(value = "/audit")
    public Result<?> audit(@RequestParam String id,
                           @RequestParam String auditStatus,
                           @RequestParam(required = false) String auditOpinion) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 添加关键参数校验
        if (StringUtils.isEmpty(id)) {
            log.warn("【供应商】审核失败: ID不能为空");
            return Result.error("ID不能为空");
        }

        boolean success = supplierService.auditSupplier(id, auditStatus, auditOpinion, sysUser.getUsername());
        if (success) {
            return Result.OK("审核成功!");
        }
        return Result.error("审核失败!");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param supplier
     */
    @ApiOperation(value = "批量导出")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Supplier supplier) {
        return super.exportXls(request, supplier, Supplier.class, "供应商");
    }

    /**
     * 通过excel导入数据 - 支持多表导入
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "批量导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        // 添加文件校验
        if (fileMap == null || fileMap.isEmpty()) {
            log.warn("【供应商】导入失败: 未上传文件");
            return Result.error("请上传文件");
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            if (file == null || file.isEmpty()) {
                log.warn("【供应商】导入失败: 上传文件为空");
                return Result.error("上传文件为空");
            }
            // 调用服务层方法处理批量导入多表数据
            return supplierService.batchImportMultiTableData(file, "SUPPLIER_QUALIFICATION");
        }

        return Result.error("文件导入失败！");
    }

    @AutoLog(value = "供应商-根据类目获取可抽签供应商")
    @ApiOperation(value = "供应商-根据类目获取可抽签供应商", notes = "供应商-根据类目获取可抽签供应商")
    @GetMapping(value = "/getLotterySuppliers")
    public Result<?> getLotterySuppliers(@RequestParam(required = false) String category) {
        // 添加类目空值校验（可选参数，但为空时仍需处理）
        if (StringUtils.isEmpty(category)) {
            log.info("【供应商】获取抽签供应商: 类目为空，返回全部供应商");
        }
        return Result.OK(supplierService.getSuppliersForLottery(category));
    }

    //通过当前用户的id，查询proc_user_supplier对应的supplierId,
    @AutoLog(value = "查询企业消息-用户")
    @ApiOperation(value = "查询企业消息-用户",notes = "查询企业消息-用户")
    @GetMapping(value = "/getSupplierIdByUserId")
    public Result<?> getSupplierIdByUserId() {
        try {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ProcUserSupplierRelation procUserSupplierRelation = procUserSupplierRelationService.getRelationBySearchKey(sysUser.getId());
            Supplier supplier = supplierService.getById(procUserSupplierRelation.getSupplierId());
            SupplierVo supplierVo =new SupplierVo();
            // 复制属性
            BeanUtils.copyProperties(supplier, supplierVo);

            List<ProcurementFile> file = procurementFileService.getFilesByBiz(procUserSupplierRelation.getSupplierId(),"supplier");
            supplierVo.setProcurementFile(file);
            List<qualification> qualifications = qualificationService.getQualificationList(procUserSupplierRelation.getSupplierId());
            supplierVo.setQualifications(qualifications);
            List<ProcurementMessage> procurementMessages =procurementMessageService.getMessagesByBusiness("supplier", procUserSupplierRelation.getSupplierId());
            //通过type和SupplierId查找对应的消息
            supplierVo.setProcurementMessage(procurementMessages);
            return Result.OK(supplierVo);
        } catch (Exception e) {
            log.error("查询用户企业消息失败, 异常信息:{}", e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    //查看供应商列表
    @AutoLog(value = "供应商-获取匹配供应商")
    @ApiOperation(value = "供应商-获取匹配供应商", notes = "供应商-获取匹配供应商")
    @GetMapping(value = "/SupplierMatch")
    public Result<?> getSupplierMatch(@RequestParam(required = false) String category) {
        // 调用Service层方法获取匹配供应商列表
        List<SupplierMatchVo> resultList = supplierService.getSupplierMatch(category);
        return Result.OK(resultList);
    }

}
